<template>
  <div v-loading="loading">
    <div class="panel">
      <div class="panel-header">{{ `订单号:${$route.params.id || '--'}` }}</div>
      <i-form
        ref="form"
        class="advert-form"
        :items="formItems"
        :rules="rules"
        :model="form"
        :inline="true"
        :layout-span="24"
        :default-span="6"
        :label-width="150"
        label-position="left"
      >
        <template slot="conbination">
          <el-form-item label="关联交易">
            <a
              v-if="form.payNum && form.payNum !== '无' && form.payNum !== ''"
              :href="`/#/transation/detail/${form.payNum}`"
              >{{ form.payNum }}</a
            >
            <div v-else>/</div>
          </el-form-item>
        </template>
      </i-form>
    </div>
    <div class="panel">
      <div class="panel-header">申诉状态</div>
      <div class="order-detail-appeal_text">
        {{ form.appeal ? form.appealText : '否' }}
      </div>
    </div>
    <div class="panel" v-if="form.appeal">
      <div class="panel-header">申诉回复</div>
      <div v-if="form.replyText !== null" class="order-detail-appeal_text">
        {{ form.replyText || '无' }}
      </div>
      <div v-else class="order-detail-appeal_reply">
        <el-input
          maxlength="255"
          show-word-limit
          v-model="replyText"
          rows="4"
          type="textarea"
          class="order-detail-appeal_reply__input"
        />
        <div class="order-detail-appeal_reply__button">
          <el-button type="primary" @click="handleReply">回复</el-button>
        </div>
      </div>
    </div>
    <div class="panel">
      <div
        id="powerDiv"
        style="width: 100%; padding: 0 15px; border-radius: 5px"
      >
        <div id="powerMain"></div>
      </div>
    </div>
  </div>
</template>
<script>
import { chargeOrderDetail, replyAppeal, getChargeRecord } from '@/api/order'
import formatter, { typeMap } from '@/utils/format'
import * as echarts from 'echarts'
import * as visualizationFun from '@/utils/visualizationFun'
import _ from 'lodash'
import echartsStyle from '@/config/echartsConstant'
import dayjs from 'dayjs'

const paymentType = {
  PREPAID: '预支付',
  AFTERPAID: '后支付',
}

export default {
  name: 'OrderDetail',
  data() {
    return {
      isCharge: false,
      isLaterPay: false,
      loading: false,
      loaded: false,
      replyText: '',
      formItems: [
        {
          label: '用户手机号：',
          value: 'userMobile',
          type: 'detail',
          ifRender: () => {
            return !!this.form.userMobile
          },
        },
        {
          label: '用户名：',
          value: 'userName',
          type: 'detail',
          ifRender: () => {
            return !!this.form.userName
          },
        },
        {
          label: '设备号：',
          value: 'deviceId',
          type: 'detail',
        },
        {
          label: '所属电站：',
          value: 'stationName',
          type: 'detail',
          ifRender: () => {
            return !!this.form.stationName
          },
        },
        {
          label: '开始充电时间：',
          value: 'chargeStartTime',
          type: 'detail',
          ifRender: () => {
            return !!this.form.chargeStartTime
          },
          formatter: () => {
            if (this.form.chargeStartTime) {
              return dayjs(this.form.chargeStartTime).format(
                'YYYY-MM-DD HH:mm:ss'
              )
            }

            return '--'
          },
        },
        {
          label: '结束充电时间：',
          value: 'chargeStopTime',
          type: 'detail',
          ifRender: () => {
            return !!this.form.chargeStopTime
          },
          formatter: () => {
            return this.calcRenderAttr({
              value: 'chargeStopTime',
              extraStatus: !this.isCharge,
              formatter: () => {
                if (this.form.chargeStopTime) {
                  return dayjs(this.form.chargeStopTime).format(
                    'YYYY-MM-DD HH:mm:ss'
                  )
                }

                return '--'
              },
            })
          },
        },
        {
          label: '充电时长(分钟)：',
          value: 'chargeDuration',
          type: 'detail',
          formatter: () => {
            // return this.form.chargeDuration !== null && this.form.chargeDuration !== '' && !isCharge ? this.form.chargeDuration : '/'
            return this.calcRenderAttr({
              value: 'chargeDuration',
              extraStatus: !this.isCharge,
            })
          },
        },
        {
          label: ' 充电电量(度)：',
          value: 'electricity',
          type: 'detail',
          formatter: () => {
            return this.calcRenderAttr({
              value: 'electricity',
              extraStatus: !this.isCharge,
            })
          },
        },
        {
          label: '代理商手机号：',
          value: 'operatorMobile',
          type: 'detail',
        },
        {
          label: '代理商用户名：',
          value: 'operatorName',
          type: 'detail',
        },
        {
          label: '套餐抵扣：',
          value: 'monthBalance',
          type: 'detail',
          formatter: () => {
            return this.calcRenderAttr({
              value: 'monthBalance',
              extraStatus: !this.isCharge,
            })
          },
        },
        {
          label: '时长卡抵扣：',
          value: 'timeCardConsume',
          type: 'detail',
          formatter: () => {
            return this.calcRenderAttr({
              value: 'timeCardConsume',
              extraStatus: !this.isCharge,
            })
          },
        },
        // {
        //   label: '和能量抵扣(点)：',
        //   value: 'andEnergyPoint',
        //   type: 'detail',
        //   formatter: () => {
        //     return this.calcRenderAttr({
        //       value: 'andEnergyPoint',
        //       extraStatus: !this.isCharge,
        //     })
        //   },
        // },
        {
          label: '充电费用(元)：',
          // value: 'chargeMoney',
          value: 'chargeFee',
          type: 'detail',
          formatter: () => {
            return this.calcRenderAttr({
              value: 'chargeFee',
              extraStatus: !this.isCharge,
            })
          },
        },
        {
          label: ' 服务费(元)：',
          value: 'serviceCost',
          type: 'detail',
          formatter: () => {
            return this.calcRenderAttr({
              value: 'serviceCost',
              extraStatus: !this.isCharge,
            })
          },
        },
        {
          label: '消费金额(元)：',
          value: 'billCost',
          type: 'detail',
          formatter: () => {
            return this.calcRenderAttr({
              value: 'billCost',
              extraStatus: !this.isCharge,
            })
          },
        },
        {
          label: '余额抵扣(元)：',
          value: 'payBalance',
          type: 'detail',
          formatter: () => {
            return this.calcRenderAttr({
              value: 'payBalance',
              extraStatus: !this.isCharge,
            })
          },
        },
        {
          label: '折扣金额(元)：',
          value: 'discountAmount',
          type: 'detail',
          ifRender: () => {
            return this.form.actId !== 0 && !this.form.voucherId
          },
        },
        {
          label: '优惠券抵扣(元)：',
          value: 'voucherDiscount',
          type: 'detail',
          formatter: () => {
            return this.calcRenderAttr({
              value: 'voucherDiscount',
              extraStatus: !this.isCharge,
            })
          },
          ifRender: () => {
            return !!this.form.voucherId
          },
        },
        {
          label: '实际需支付金额(元)：',
          value: 'payMoney',
          type: 'detail',
          formatter: () => {
            return this.calcRenderAttr({
              value: 'payMoney',
              extraStatus: !this.isCharge,
            })
          },
        },
        {
          label: '订单状态：',
          value: 'orderStatus',
          type: 'detail',
          formatter: () => {
            console.log(this.form.orderStatus)
            return this.form.orderStatus && this.form.orderStatus !== ''
              ? typeMap.chargeOrderStatus[this.form.orderStatus]
              : '/'
          },
        },
        {
          label: '充电来源：',
          value: 'tokenType',
          type: 'detail',
          formatter,
          ifRender: () => {
            return !!this.form.tokenType
          },
        },
        {
          label: '结束原因：',
          value: 'chargeStatus',
          type: 'detail',
          formatter: () => {
            return this.calcRenderAttr({
              value: 'chargeStatus',
              formatter: (val) => {
                return typeMap.chargeStatus[val]
              },
              extraStatus: !this.isCharge,
            })
          },
        },
        {
          label: '支付类型：',
          value: 'paymentType',
          type: 'detail',
          formatter: () => {
            if (this.form.paymentType === null || this.form.paymentType === '')
              return '/'
            return paymentType[this.form.paymentType]
          },
        },
        {
          label: '支付状态：',
          value: 'payStatus',
          type: 'detail',
          formatter: () => {
            return this.isLaterPay && this.isCharge
              ? '/'
              : typeMap.payStatus[this.form.payStatus]
          },
        },
        {
          slot: 'conbination',
        },
        {
          label: '计费模式：',
          value: 'staPriceType',
          type: 'detail',
          formatter: () => {
            return typeMap.staPriceType[this.form.staPriceType]
          },
        },
      ],
      rules: {},
      form: {},
    }
  },
  methods: {
    renderCharts(data) {
      if (!Array.isArray(data.unifiedSlotMessages)) return
      if (data.unifiedSlotMessages.length > 0) {
        let powerChart = echarts.init(document.getElementById('powerMain'))
        let powerDiv = document.getElementById('powerDiv')
        powerDiv.style.height = '400px'

        window.onresize = () => {
          visualizationFun.chartsSizeSet(powerDiv, powerChart)
        }

        visualizationFun.chartsSizeSet(powerDiv, powerChart)

        data.startTime &&
          data.unifiedSlotMessages.length &&
          data.unifiedSlotMessages.unshift({
            time: data.startTime,
            meanPower: data.unifiedSlotMessages[0].meanPower,
          })
        this.form.chargeStopTime &&
          data.unifiedSlotMessages.length &&
          data.unifiedSlotMessages.push({
            time: this.form.chargeStopTime,
            meanPower:
              data.unifiedSlotMessages[data.unifiedSlotMessages.length - 1]
                .meanPower,
          })
        let powerXAxis = []
        let powerData = []
        // let powerArr = []

        let time = ''
        // let index = 0
        data.unifiedSlotMessages.forEach((item) => {
          time = dayjs(item.time.replace(/-/g, '/'))
          let temp =
            visualizationFun.add0(time.hour()) +
            ':' +
            visualizationFun.add0(time.minute())
          powerXAxis.push(temp)
          powerData.push(parseFloat(item.meanPower).toFixed(2))
          // if (
          //   dayjs(item.time).diff(dayjs(item.time), 'minute') < 6 ||
          //   dayjs(item.time).diff(dayjs(item.time), 'minute') > 10
          // ) {
          //   powerArr[index].push(
          //     powerData.concat(
          //       Array(data.unifiedSlotMessages.length - 1 - i).fill('-')
          //     )
          //   )
          //   powerData = Array(i + 1).fill('-')
          //   index++
          // }
        })
        powerChart.setOption({
          title: {
            text: '功率曲线(W)',
            textStyle: {
              color: '#4D4D4D',
              fontSize: '14',
              fontWeight: 'normal',
            },
            left: '10',
            top: '16',
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'line',
              lineStyle: {
                width: 2,
                color: '#4C71F9',
                opacity: 0.5,
              },
            },
          },
          grid: _.assign({}, echartsStyle.grid, {
            left: '10',
          }),
          yAxis: [
            _.assign(
              {
                type: 'value',
                show: true,
              },
              echartsStyle.yAxisObj
            ),
          ],
          xAxis: _.assign({}, echartsStyle.xAxisObj, {
            type: 'category',
            data: powerXAxis,
            show: true,
          }),
          series: [
            _.assign({
              name: '功率(W)',
              type: 'line',
              showSymbol: false,
              smooth: 'true',
              lineStyle: {
                color: '#4476F9',
              },
              itemStyle: {
                color: '#4476F9',
              },
              areaStyle: {
                color: '#4678f9',
                opacity: '0.1',
              },
              data: powerData,
            }),
          ],
        })
      }
    },
    handleReply() {
      if (!this.replyText || this.replyText === '') {
        this.$message({
          type: 'warning',
          showClose: true,
          message: '输入内容不能为空!',
        })

        return
      }

      // this.loading = true
      replyAppeal({
        billNum: this.$route.params.id,
        replyText: this.replyText,
      })
        .then(() => {
          this.$message({
            type: 'success',
            showClose: true,
            message: '回复成功!',
          })

          this.getDetails()
        })
        .catch((err) => {
          console.log(err)
        })
    },
    calcRenderAttr(
      options = {
        value: '',
        formatter: null,
        default: '/',
        extraStatus: true,
      }
    ) {
      let option = {
        value: '',
        formatter: null,
        default: '/',
        extraStatus: true,
        ...options,
      }
      if (
        option.value === '' ||
        !Object.prototype.hasOwnProperty.call(this.form, option.value)
      )
        return option.default

      return this.form[option.value] !== null &&
        this.form[option.value] !== '' &&
        option.extraStatus
        ? typeof option.formatter === 'function'
          ? option.formatter(this.form[option.value])
          : this.form[option.value]
        : option.default
    },
    getChargeRecords() {
      this.loading = true
      getChargeRecord({
        billNum: this.$route.params.id,
        deviceId: this.form.deviceId,
      })
        .then((res) => {
          this.renderCharts(res)
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.loading = false
        })
    },
    getDetails() {
      if (!this.$route.params.id) return

      this.loading = true
      chargeOrderDetail({
        billNum: this.$route.params.id,
      })
        .then((res) => {
          this.isCharge = res.orderStatus === typeMap.chargeOrderStatus.ONGOING
          this.isLaterPay = res.paymentType === 'AFTERPAID'
          this.form = res

          this.getChargeRecords()
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.loading = false
          this.loaded = true
        })
    },
  },
  mounted() {
    this.getDetails()
  },
}
</script>
<style lang="scss" scoped>
.order-detail-appeal_text {
  padding: 0 40px;
}
.order-detail-appeal_reply {
  padding: 0 40px;

  .order-detail-appeal_reply__button {
    padding-top: 20px;
    display: flex;
    justify-content: flex-end;
    width: 100%;
  }
}
</style>
<style lang="scss">
.advert-form {
  padding-left: 20px;
  .el-form-item__content {
    span {
      color: #988ca4;
    }
  }
}
</style>
